package org.sixdog.mcsit.filter;

import org.sixdog.mcsit.service.TokenService;
import org.sixdog.mcsit.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@WebFilter(urlPatterns = "/*")
@Order(value = 1)
public class GlobalFilter implements Filter {

    @Autowired
    TokenService tokenService;

    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/user/registerEmail","/user/registerUser","/user/loging","/user/getCaptcha")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
        boolean allowedPath = ALLOWED_PATHS.contains(path);


        if (allowedPath || request.getMethod().equals("OPTIONS")) {
            //不需要处理的url进入的方法
            chain.doFilter(req, res);
        }
        else {
            //需要处理的url进入的方法
            String tokenKey = request.getHeader("mcsittoken");
            if (!StringUtils.isBlank(tokenKey) && tokenService.hasToken(tokenKey)){
                chain.doFilter(req, res);
            }
        }
    }

    @Override
    public void destroy() {

    }
}

